package cn.ch.pet.service.impl;

import cn.ch.basic.service.impl.BaseServiceImpl;
import cn.ch.pet.domain.PetType;
import cn.ch.pet.mapper.PetTypeMapper;
import cn.ch.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Why
 * @since 2022-02-24
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;
    @Override
    public List<PetType> queryTree() {
        //获取所有的菜单信息
        List<PetType> all = petTypeMapper.loadAll();
        //创建需要返回的顶层集合
        List<PetType> FirstPetType = new ArrayList<>();
        //将所有的菜单转储为map集合
        Map<Long, PetType> typeMap = all.stream().collect(Collectors.toMap(PetType::getId, o -> o));
        for (PetType pt: all) {
            //找出树的顶层
            if (pt.getPid()==null){
                FirstPetType.add(pt);
            }else {
                //找到自己的父级  并将自己加进去
                PetType parent = typeMap.get(pt.getPid());
                if (parent!=null)
                    //把自己添加进去
                    parent.getChildren().add(pt);
            }
        }
        return FirstPetType;//返回最顶层
    }
}
